/** 
 * LexFtpClient2.java
 * @author Lex
 * 2007-9-6 ����09:05:37
 */
package org.lex.net.ftp;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.swing.Timer;

import org.lex.net.Password;
import org.lex.net.ftp.util.FTPClientConfig;


public class LexFTPClient extends RFC959FTPClient implements IFTPClient {
	private Timer antiIdleTimer = null;
	private int keepAliveDelay = 30000;
	private boolean keepAlive = true;
	private FTPURL url = FTPURL.FAKE_URL;

	public LexFTPClient() {
		this(FTPClientConfig.DEFAULT_CONFIG);
	}

	public LexFTPClient(FTPClientConfig config) {
		super();
		if (null == config)
			config = FTPClientConfig.DEFAULT_CONFIG;
		// load configurations
		this.setServerCharset(config.charset);
		this.setConnectTimeout(config.connectTimeout);
		this.setSoTimeout(config.readTimeout);
		this.keepAlive = config.keepAlive;
		this.keepAliveDelay = config.keepAliveDelay;
		this.antiIdleTimer = new Timer(keepAliveDelay, new AntiIdleTimerListener());
	}

	public FTPURL getURL() {
		return url;
	}

	/***************************************************************************
	 * Connection Methods
	 **************************************************************************/
	@Override
	public void openServer(String host) throws UnknownHostException, IOException {
		this.openServer(host, RawFTPClient.DEFAULT_FTP_PORT);
	}

	@Override
	public void openServer(String host, int port) throws UnknownHostException, IOException {
		this.openServer(InetAddress.getByName(host), port);
	}

	@Override
	public void openServer(InetAddress host, int port) throws IOException {
		super.openServer(host, port);
		this.url = new FTPURL(host.getHostAddress(), port);
	}

	@Override
	public void closeServer() throws IOException {
		antiIdleTimer.stop();
		this.url = FTPURL.FAKE_URL;
		super.closeServer();
	}

	public void login(Password auth) throws IOException {
		super.login(auth.getUserName(), auth.getPassword());
		this.url = new FTPURL(auth, url.getHost(), url.getPort());
	}

	/***************************************************************************
	 * 
	 **************************************************************************/
	public void setKeepAlive(boolean keepAlive) {
		this.keepAlive = keepAlive;
		if (true == keepAlive) {
			this.antiIdleTimer.restart();
		} else {
			this.antiIdleTimer.stop();
		}
	}

	public void setPassiveMode(boolean pasv) {
	}

	class AntiIdleTimerListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			if (true == keepAlive && true == isServerOpen())
				try {
					noop();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
		}
	}
}
